package com.caseProject.puremvc.mediator.gui
{
	import com.caseProject.puremvc.mediator.states.graphicStates.EditionState;
	import com.caseProject.puremvc.mediator.states.graphicStates.IGraphicState;
	import com.caseProject.puremvc.mediator.states.graphicStates.IdleState;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class Graphic extends Sprite
	{
		private var state:IGraphicState;
		private var _id:int;
		private var _vo:Object;
		private var _enableDrag:Boolean;

		private var del:NativeMenuItem;
		private var edit:NativeMenuItem;
		
		public function Graphic()
		{
			super();
			
			this.setCurrentState(IdleState);
			
			var nativeMenu:NativeMenu = new NativeMenu();			
			del = new NativeMenuItem("Excluir");
			edit = new NativeMenuItem("Editar");
			
			this.contextMenu = nativeMenu;
			
			nativeMenu.addItem(del);			
			nativeMenu.addItem(edit);
			
			this.edit.addEventListener(Event.SELECT, onSelectEdit);
			this.del.addEventListener(Event.SELECT, onSelectDel);			
		}
		
		public function onAddedToStage():void
		{
			this.edit.addEventListener(Event.SELECT, onSelectEdit);
			this.del.addEventListener(Event.SELECT, onSelectDel);
		}
		
		protected function onSelectEdit(event:Event):void
		{
			this.clearSelection ();
			this.setCurrentState(EditionState);			
		}
		
		private function clearSelection ():void {
			var container:DisplayObjectContainer = this.parent;
			var sg:Graphic;
			if (container != null) {
				for (var i:int = 0; i < container.numChildren; i++)  {
					var graphic:Graphic = container.getChildAt(i) as Graphic;
					if (graphic != null && graphic is Graphic) {
						graphic.setCurrentState(IdleState);
					}
				}
			}
		}
		
		public function draw():void 
		{
			var graphFormat:GraphicFormat = new GraphicFormat ();
			graphFormat.doFormat(this);
		}
		
		public function setCurrentState (Class:Class):void
		{
			this.state = new Class() as IGraphicState;
			this.state.setVisual(this);
			this.state.action(this);
		}
		
		/**
		 * Function overridden by each type of Graphic
		 * */
		protected function onSelectDel(event:Event):void {}
		
		public function get vo():Object
		{
			return _vo;
		}

		public function set vo(value:Object):void
		{
			_vo = value;
		}

		public function get id():int
		{
			return _id;
		}

		public function set id(value:int):void
		{
			_id = value;
		}
		
		public function get enableDrag():Boolean
		{
			return _enableDrag;
		}
		
		public function set enableDrag(value:Boolean):void
		{
			_enableDrag = value;
		}
	}
}